<%--
  Created by IntelliJ IDEA.
  User: sicilin
  Date: 2017/8/4
  Time: 17:05
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ include file="../commons-easyui.jsp"%>
<html>
<head>
    <title>角色管理</title>
    <style type="text/css">
        #roleForm > div{
            margin: 10px 0px;
        }
        #roleForm > div > .easyui-validatebox{
            height:25px;
        }
    </style>

    <script type="text/javascript" src="<%=basePath%>common/script/customize/customize-old.js"></script>
    <script type="text/javascript" src="<%=basePath%>common/script/customize/object/object.js"></script>
    <script type="text/javascript">
        /*------- 全局变量部分 -------*/
        var formMode ='';
        var roleAuth = {};
        var checkBoxClassMapped = ['tree-checkbox0','tree-checkbox1','tree-checkbox2'];

        $(document).ready(function(){
            initRoleTable();
        });
        function initCompanyCombo(){
            if(currentUser.companyId != 0){
                return;
            }
            tmsObject.treeCombo($('#companyCombo'),["mainCompany","ourCompany","upCompany","downCompany"],true);
        }

        function initRoleTable(){
            $('#roleTable').datagrid({
                url:basePath+'roleAction/searchRoleLimit.json'
                ,queryParams:{"text":''}
                ,method:'post'
                ,rownumbers:true
                ,pagination:true
                ,fit:true
                ,singleSelect:true
                ,border:false
                ,toolbar:'#roleToolbar'
                ,pageSize:20
                ,pageList:[20,50,100]
                ,columns:[[
                    {field:'roleCode',title:'角色编号'}
                    ,{field:'roleName',title:'角色名称'}
                    ,{field:'description',title:'角色说明'}
                    ,{field:'level',title:'角色权限等级'}
                    ,{field:'company',title:'所属公司',width:75,formatter:function(value,row,index){
                        return value.companyName+"("+value.companyCode+")";
                    }}
                ]]
            });
        }

        function searchRole(mode){
            var text = $('#searchTextBox').textbox('getText');
            $('#roleTable').datagrid(mode,{"text":text});
        }


        function setFormSubmitMode(mode){
            $('#roleForm').form('clear');
            formMode = mode;
            var selectRole = $('#roleTable').datagrid('getSelected');
            if(currentUser.companyId == 0){
                initCompanyCombo();
            }else{
                $('#companyDiv').remove();
            }
            if(formMode == 'add'){


            }else if(formMode == 'edit'){
                if($.isEmptyObject(selectRole)){
                    $.messager.alert('注意','没有选择的角色','warning',emptyFn());
                    return false;
                }
                $('#roleCode').val(selectRole.roleCode);
                $('#roleName').val(selectRole.roleName);
                $('#description').textbox('setValue',selectRole.description);

            }else{
                return false;
            }
        }

        function submitRoleForm(){
            var param = getJSONFormData('roleForm');
            if(formMode == 'add'){
                tmsAjax({
                    url:basePath+'roleAction/addRole.json'
                    ,type:'post'
                    ,data:JSON.stringify(param)
                    ,success:function(data){
                        if(!isBlank(data)){
                            easyuiAlert('添加成功','info');
                            closeDialog('roleDialog',searchRole,'reload');
                        }
                    }
                });
            }else if(formMode == 'edit'){
                var selectRole = $('#roleTable').datagrid('getSelected');
                param.roleId = selectRole.roleId;
                tmsAjax({
                    url:basePath+'roleAction/updateRole.json'
                    ,type:'post'
                    ,data:JSON.stringify(param)
                    ,success:function(data){
                        if(!isBlank(data)){
                            easyuiAlert('修改成功','info');
                            closeDialog('roleDialog',searchRole,'reload');
                        }
                    }
                });
            }
        }



        function getRoleAuth(){
            var selectRole = $('#roleTable').datagrid('getSelected');
            if(isBlank(selectRole)){
                easyuiAlert('没有选择的角色','warning');
                return false;
            }
            return true;
//            var flag = true;
//            tmsAjax({
//                url:basePath+'roleAction/getRoleAuthIds.json?roleId='+selectRole.roleId
//                ,type:'post'
//                ,dataType:'json'
//                ,async:false
//                ,success:function (data) {
//                    if(data == null){flag = false;}
//                    roleAuth[selectRole.roleId]=data;
//                }
//                ,error:function(){
//                    flag = false;
//                }
//            });
//            $.ajax({
//                url:basePath+'roleAction/getRoleAuthIds.json'
//                ,type:'post'
//                ,data:{'roleId':selectRole.roleId}
//                ,async:false
//                ,dataType:'json'
//                ,success:function (ajaxResponse) {
//                   var data = getAjaxReturnData(ajaxResponse);
//                   if(data == null){flag = false;}
//                   roleAuth[selectRole.roleId]=data;
//                }
//                ,error:function () {
//                    easyuiAlert('查询权限错误！','error');
//                    flag=false;
//                }
//            });
//            return flag;

        }

        function saveRoleAuth() {
            var selectRole = $('#roleTable').datagrid('getSelected');
            var allAuth = $('span[id^="check_"][id!="check_0"][class!="tree-checkbox tree-checkbox0"]');
            var saveAuths = [];
            $.each(allAuth,function (index,auth) {
                var authId = $(auth).attr('authid');
                if($(auth).attr('id')=='check_0'){
                    return true;
                }
                if($(auth).hasClass(checkBoxClassMapped[1])){
                    var auth = {'roleId':selectRole.roleId,'authId':authId,'checked':1};
                    saveAuths.push(auth);
                }else if($(auth).hasClass(checkBoxClassMapped[2])){
                    var auth = {'roleId':selectRole.roleId,'authId':authId,'checked':2};
                    saveAuths.push(auth);
                }
            });
            tmsAjax({
                url:basePath+'roleAction/addRoleAuth.json'
                ,data:JSON.stringify(saveAuths)
                ,type:'post'
                ,success:function (data) {
                    easyuiAlert('保存成功！','info');
                },error:function () {
                    //easyuiAlert('保存失败！','error');
                }

            });

        }
    </script>


    <!-- treegrid 自定义插件部分  -->
    <script type="text/javascript">
        function initRoleAuthTree(){
            var selectRole = $('#roleTable').datagrid('getSelected');

            if($('#roleAuthTree').data('initialization') == 'complete'){
                $('#roleAuthTree').treegrid('load',{'roleId':selectRole.roleId});
                return;
            }
            $('#roleAuthTree').treegrid({
                url:basePath+'authAction/getTreeAuthWidthCheckedByRoleId.json'
                ,queryParams:{'roleId':selectRole.roleId}
                ,method:'post'
                ,idField:'authId'
                ,treeField:'authName'
                ,border:false
                ,toolbar:'#authTreeToolbar'
                ,selectOnCheck:false
                ,cache:false
                ,checkOnSelect:false
                //,checkbox:true
                ,columns:[[
                    {field:'authName',title:'权限名称',formatter:function (value,row,index) {
                        var checkClass = checkBoxClassMapped[row.checked == null?0:row.checked];

                        var treebox = '<span onclick="changeCheck('+row.authId+')" authid="'+row.authId+'" parentid="'+row.parentId+'" id="check_'+row.authId+'" class="tree-checkbox '+checkClass+'"></span> ';
                        return treebox + value;
                    }}
                    ,{field:'authCode',title:'权限编码'}
                    ,{field:'authTotalCode',title:'权限绝对路径'}
                ]]
                ,fit:true
            });
            $('#roleAuthTree').data('initialization','complete');
        }

        function changeCheck(nodeId){
            var checkbox = $('#check_'+nodeId);
            var change = -1;
            if(checkbox.hasClass(checkBoxClassMapped[0]) || checkbox.hasClass(checkBoxClassMapped[2])){
                change = 1;
            }else if(checkbox.hasClass(checkBoxClassMapped[1])){
                change = 0;
            }

            switch (change){
                case 1 : //被选中
                    check1(nodeId);break;
                case 0 :
                    check0(nodeId);break;

            }

        }

        function check1(nodeId,cycle){
            var checkbox = $('#check_'+nodeId);
            changeStatus(nodeId,1);

            var brothers = $('span[parentId='+checkbox.attr('parentid')+']');
            var parentCheck = 1;
            //判断兄弟是否全选
            if(nodeId > 0){
                $.each(brothers,function (index,brother) {
                    if($(brother).attr('id') == "check_"+nodeId){return true;}
                    if ($(brother).hasClass(checkBoxClassMapped[0]) || $(brother).hasClass(checkBoxClassMapped[2])){
                        parentCheck = 2;return false;
                    }
                });
                if(parentCheck == 2){
                    check2(checkbox.attr('parentid'));
                }else{
                    check1(checkbox.attr('parentid'),false);
                }
            }

            if(cycle == false){return ;}
            var childs = $('#roleAuthTree').treegrid('getChildren',nodeId);

            //全选子集
            $.each(childs,function (index,child) {
                if(child.authId == 0){return;}
                check1(child.authId,false);
            });

        }

        function check0(nodeId,cycle){
            var checkbox = $('#check_'+nodeId);
            changeStatus(nodeId,0);


            var brothers = $('span[parentId='+checkbox.attr('parentid')+']');
            var parentCheck = 1;
            //判断兄弟是否全选
            if(nodeId > 0){
                $.each(brothers,function (index,brother) {
                    if($(brother).attr('id') == "check_"+nodeId){return true;}
                    if ($(brother).hasClass(checkBoxClassMapped[1]) || $(brother).hasClass(checkBoxClassMapped[2])){
                        parentCheck = 2;return false;
                    }
                });
                if(parentCheck == 2){
                    check2(checkbox.attr('parentid'));
                }else{
                    check0(checkbox.attr('parentid'),false);
                }
            }


            if(cycle == false){return ;}
            var childs = $('#roleAuthTree').treegrid('getChildren',nodeId);
            $.each(childs,function (index,child) {
                if(child.authId == 0){return;}
                check0(child.authId,false);
            });

        }

        function check2(nodeId){
            var checkbox = $('#check_'+nodeId);
            changeStatus(nodeId,2);

            var parentid = checkbox.attr('parentid');
            if(parentid != 'null'){check2(parentid);}
        }
        function isCheckstatus(nodeId,status) {
            return $('#check_'+nodeId).hasClass(checkBoxClassMapped[status]);
        }

        function changeStatus(nodeId,status){
            var checkbox = $('#check_'+nodeId);
            checkbox.removeClass(checkBoxClassMapped[0]);
            checkbox.removeClass(checkBoxClassMapped[1]);
            checkbox.removeClass(checkBoxClassMapped[2]);
            checkbox.addClass(checkBoxClassMapped[status]);
        }



    </script>
</head>
<body>
    <div class ="easyui-layout" data-options="fit:true">
        <%--<div data-options="region:'east',title:'角色所有权限',split:true" style="width:200px;"> </div>--%>
        <div data-options="region:'center',title:'角色管理'" style="background:#eee;">
            <table id="roleTable"></table>
        </div>
    </div>
    <!-- dialog区域 -->
    <div id = "roleDialog" style="display: none">
        <form id="roleForm" style="padding:10px;">
            <div>
                <label>角色编码：</label>
                <input id="roleCode" name="roleCode" class="easyui-validatebox textbox" />
            </div>
            <div>
                <label>角色名称：</label>
                <input id="roleName" name="roleName" class="easyui-validatebox textbox" />
            </div>
            <div>
                <label>权限等级：</label>
                <select name="level">
                    <option value="0">0</option>
                    <option value="1">1</option>
                    <option value="2">2</option>
                    <option value="3">3</option>
                </select>
            </div>
            <div id = "companyDiv">
                <label>所属公司</label>
                <input id = "companyCombo" name="companyId" />
            </div>
            <div>
                <label>角色介绍：</label>
                <input id="description" name="description" class="easyui-textbox" data-options="multiline:true,height:100" />
            </div>
            <div style="height:35px;">
                <a class="easyui-linkbutton" data-options="iconCls:'icon-ok',fit:true" onclick="submitRoleForm()">提交</a>
            </div>
        </form>
    </div>

    <div id="roleAuthDialog" style="display: none;width: 500px;height: 400px;">
        <table id = "roleAuthTree">
        </table>
    </div>

    <!-- toolbar 区域 -->
    <div id ="roleToolbar">
        <input style="width:180px;" id="searchTextBox" class="easyui-textbox" data-options="buttonIcon:'icon-search',onClickButton:function(){searchRole('load')}" />
        <a class="easyui-linkbutton" data-options="iconCls:'icon-add'" onclick="openOrInitDialog('roleDialog','角色管理',null,null,setFormSubmitMode,'add')" style="margin-left: 10px;">新建角色</a>
        <a class="easyui-linkbutton" data-options="iconCls:'icon-edit'" onclick="openOrInitDialog('roleDialog','角色管理',null,null,setFormSubmitMode,'edit')" >修改角色</a>
        <a class="easyui-linkbutton" data-options="iconCls:'icon-lock'">重置密码</a>
        <a class="easyui-linkbutton" data-options="iconCls:'icon-lock'">禁/启用</a>
        <a class="easyui-linkbutton" data-options="iconCls:'icon-man'" onclick="openOrInitDialog('roleAuthDialog','角色权限管理',initRoleAuthTree,null,getRoleAuth)">角色权限</a>
    </div>

    <div id = "authTreeToolbar">
        <a class="easyui-linkbutton" data-options="iconCls:'icon-save'"  style="margin-left: 10px;" onclick="saveRoleAuth()">保存权限</a>
    </div>

</body>
</html>
